import { observable, action, makeAutoObservable, runInAction } from 'mobx'
import { find, pick } from 'lodash'

class Video {
  constructor() {
    // observable,触发视图改变
    makeAutoObservable(this)
  }
  @observable videoSize = { w: 800, h: 500 }
  @observable screenArr = []
  @observable curScreenId = null
  // 正在播放视频的分屏：[{id, status, player}]
  @observable playingScreens = []
  // live or record
  @observable videoType = 'live'
  @observable mode = 4
  @observable lastMode = 4

  @action setVideoSize(w, h) {
    runInAction(() => {
      this.videoSize = { w, h }
    })
  }
  @action setScreenArr(array) {
    runInAction(() => {
      this.screenArr = array
    })
  }
  @action setScreensArrayByParams(id, strArr, valArr) {
    const screen = this.findScreenById(id)
    strArr.forEach((val, i) => {
      screen[strArr[i]] = valArr[i]
    })
    console.log(screen.id)
  }
  @action exchangeScreen(dragId, dropId) {
    runInAction(() => {
      const dragObject = this.findScreenById(dragId)
      const dropObject = this.findScreenById(dropId)
      const params = ['id']
      const temp = { ...pick(dragObject, params) }
      for (const item of params) {
        dragObject[item] = dropObject[item]
      }
      for (const item of params) {
        dropObject[item] = temp[item]
      }
    })
  }
  @action setScreenByParams(id, str, val) {
    const screen = find(this.screenArr, ['id', id])
    if (screen) {
      for (let i = 0; i < str.length; i++) {
        screen[str[i]] = val[i]
      }
    }
  }
  @action addPlayer(id, player) {
    const screen = this.findScreenById(id)
    if (screen) {
      screen.player = player
    }
  }
  @action removePlayer(id) {
    const screen = this.findScreenById(id)
    if (screen) {
      screen.player = undefined
    }
  }
  // 播放状态（stop、play、pause)
  @action setStatus(id, status) {
    const screen = this.findScreenById(id)
    if (screen) {
      screen.status = status
    }
  }
  @action setCurScreenId = async (id) => {
    const _id = await id
    // 由于拖拽会频繁触发，所以要用到runInAction
    runInAction(() => {
      this.curScreenId = _id
    })
  }
  @action setVideoType(str) {
    runInAction(() => {
      this.videoType = str
    })
  }
  @action setPlayingScreens(val) {
    runInAction(() => {
      this.playingScreens = val
    })
  }
  @action findScreenById(id) {
    return find(this.screenArr, ['id', id])
  }
  @action setMode(val) {
    this.mode = val
  }
  @action setLastMode(val) {
    this.lastMode = val
  }
}

export default new Video()
